//
//  GJViewController.m
//  ObjcGoNew
//
//  Created by 邢伟新 on 2021/4/27.
//

#import "GJViewController.h"
#import "GJPerson.h"

/*
 归档解档:将数据写入文件,将文件中读取出来
 */

@interface GJViewController ()

@end

@implementation GJViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"归档解档";
    self.view.backgroundColor = [UIColor whiteColor];
    //[self userDefaults];
    [self setStandBox];
}

-(void)userDefaults{
    GJPerson *model = [[GJPerson alloc]init];
    model.name = @"xwx";
    model.age = @28;
    model.hejght = @(172.0f);
    
    /*
     直接存model会崩溃
     [[NSUserDefaults standardUserDefaults]setObject:model forKey:@"xingweixin"];
     [[NSUserDefaults standardUserDefaults]synchronize];
     */
    
    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:model];
    [[NSUserDefaults standardUserDefaults]setObject:data forKey:@"xingweixin"];
    [[NSUserDefaults standardUserDefaults]synchronize];
    
    
    
    
    NSData *dataUnArc = [[NSUserDefaults standardUserDefaults]objectForKey:@"xingweixin"] ;
    GJPerson *p = [NSKeyedUnarchiver unarchiveObjectWithData:dataUnArc];
    NSLog(@"----%@----%@-----%@",p.name,p.age,p.hejght);
    NSLog(@"-----%s----",__func__);
}

-(void)setStandBox{
    
    //可写入沙盒的plist文件或者data文件
    
    GJPerson *model = [[GJPerson alloc]init];
    model.name = @"xwx";
    model.age = @28;
    model.hejght = @(172.0f);
    
    //这里以temp路径为例，存到temp路径下
    NSString *temp = NSTemporaryDirectory();
    NSString *filePath = [temp stringByAppendingPathComponent:@"obj.data"];
    NSLog(@"%@", filePath);
    //归档
    [NSKeyedArchiver archiveRootObject:model toFile:filePath];
    
     GJPerson *person = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
     NSLog(@"name = %@, age = %@",person.name,person.age);
    
    
    
    
}


@end
